/**
 * 通用工具函数
 * 包含常用工具方法，如toast、modal、loading等
 */

/**
 * 显示toast提示
 * @param {string} title - 提示内容
 * @param {string} icon - 图标类型
 * @param {number} duration - 持续时间(ms)
 */
export const showToast = (title, icon = 'none', duration = 2000) => {
  uni.showToast({
    title,
    icon,
    duration
  })
}

/**
 * 显示loading
 * @param {string} title - loading文字
 * @param {boolean} mask - 是否显示透明蒙层
 */
export const showLoading = (title = '加载中...', mask = true) => {
  uni.showLoading({
    title,
    mask
  })
}

/**
 * 隐藏loading
 */
export const hideLoading = () => {
  uni.hideLoading()
}

/**
 * 显示模态框
 * @param {string} title - 标题
 * @param {string} content - 内容
 * @param {boolean} showCancel - 是否显示取消按钮
 * @param {string} confirmText - 确认按钮文字
 * @param {string} cancelText - 取消按钮文字
 * @returns {Promise<boolean>} - 返回用户选择
 */
export const showModal = ({
  title = '提示',
  content = '',
  showCancel = true,
  confirmText = '确定',
  cancelText = '取消'
}) => {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      showCancel,
      confirmText,
      cancelText,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

/**
 * 显示操作菜单
 * @param {Array<string>} itemList - 菜单列表
 * @returns {Promise<number>} - 返回选择的索引
 */
export const showActionSheet = (itemList) => {
  return new Promise((resolve, reject) => {
    uni.showActionSheet({
      itemList,
      success: (res) => {
        resolve(res.tapIndex)
      },
      fail: (res) => {
        reject(res)
      }
    })
  })
}

/**
 * 跳转页面
 * @param {string} url - 页面路径
 * @param {string} type - 跳转类型(navigateTo, redirectTo, switchTab, reLaunch)
 */
export const navigateTo = (url, type = 'navigateTo') => {
  const methods = {
    navigateTo: uni.navigateTo,
    redirectTo: uni.redirectTo,
    switchTab: uni.switchTab,
    reLaunch: uni.reLaunch
  }
  
  if (methods[type]) {
    methods[type]({ url })
  }
}

/**
 * 返回上一页
 * @param {number} delta - 返回的页面数
 */
export const navigateBack = (delta = 1) => {
  uni.navigateBack({ delta })
}

/**
 * 格式化日期
 * @param {Date|string|number} date - 日期
 * @param {string} format - 格式
 * @returns {string} - 格式化后的日期
 */
export const formatDate = (date, format = 'YYYY-MM-DD') => {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 格式化时间（相对时间）
 * @param {Date|string|number} date - 日期
 * @returns {string} - 相对时间描述
 */
export const formatRelativeTime = (date) => {
  if (!date) return ''
  
  const now = new Date()
  const target = new Date(date)
  const diff = now - target
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return Math.floor(diff / minute) + '分钟前'
  } else if (diff < day) {
    return Math.floor(diff / hour) + '小时前'
  } else if (diff < week) {
    return Math.floor(diff / day) + '天前'
  } else {
    return formatDate(date, 'MM-DD')
  }
}

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} wait - 等待时间(ms)
 * @returns {Function} - 防抖后的函数
 */
export const debounce = (func, wait = 300) => {
  let timeout
  return function (...args) {
    clearTimeout(timeout)
    timeout = setTimeout(() => func.apply(this, args), wait)
  }
}

/**
 * 节流函数
 * @param {Function} func - 要执行的函数
 * @param {number} delay - 延迟时间(ms)
 * @returns {Function} - 节流后的函数
 */
export const throttle = (func, delay = 300) => {
  let lastTime = 0
  return function (...args) {
    const now = Date.now()
    if (now - lastTime > delay) {
      lastTime = now
      func.apply(this, args)
    }
  }
}

/**
 * 检查对象是否为空
 * @param {Object} obj - 要检查的对象
 * @returns {boolean} - 是否为空
 */
export const isEmpty = (obj) => {
  if (obj == null) return true
  if (typeof obj === 'string') return obj.trim() === ''
  if (Array.isArray(obj)) return obj.length === 0
  if (typeof obj === 'object') return Object.keys(obj).length === 0
  return false
}

/**
 * 复制文本到剪贴板
 * @param {string} text - 要复制的文本
 */
export const copyToClipboard = (text) => {
  return new Promise((resolve, reject) => {
    uni.setClipboardData({
      data: text,
      success: () => {
        showToast('复制成功')
        resolve()
      },
      fail: (error) => {
        showToast('复制失败')
        reject(error)
      }
    })
  })
}

/**
 * 获取设备信息
 * @returns {Object} - 设备信息
 */
export const getSystemInfo = () => {
  return new Promise((resolve) => {
    uni.getSystemInfo({
      success: (res) => {
        resolve(res)
      },
      fail: () => {
        resolve({
          platform: 'unknown',
          system: 'unknown',
          model: 'unknown'
        })
      }
    })
  })
}

/**
 * 检查是否为空数组或对象
 * @param {Array|Object} value - 要检查的值
 * @returns {boolean} - 是否为空
 */
export const isEmptyValue = (value) => {
  if (value == null) return true
  if (typeof value === 'string') return value.trim() === ''
  if (Array.isArray(value)) return value.length === 0
  if (typeof value === 'object') {
    return Object.keys(value).length === 0
  }
  return false
}

/**
 * 深拷贝对象
 * @param {Object} obj - 要拷贝的对象
 * @returns {Object} - 拷贝后的对象
 */
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const cloned = {}
    Object.keys(obj).forEach(key => {
      cloned[key] = deepClone(obj[key])
    })
    return cloned
  }
}